package com.store.app.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.text.Html;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.store.app.BaseActivity;
import com.store.app.ExitApplication;
import com.store.app.R;
import com.store.app.adapter.OneYuanBuyDetailsAdapter;
import com.store.app.bean.AllBean;
import com.store.app.bean.EventBusBean;
import com.store.app.bean.OneYuanBuyDetailsBean;
import com.store.app.bean.OneYuanBuyUpdateBean;
import com.store.app.net.NetRequest;
import com.store.app.net.ifc.IOnHttpListener;
import com.store.app.utils.ToastUtils;
import com.store.app.utils.UserTokenUtils;
import com.store.app.utils.Utils;
import com.store.app.widget.AutoListView;

import org.json.JSONObject;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import de.greenrobot.event.EventBus;

/**
 * Created by Administrator on 2016/5/11.
 */
public class GGLDetailsActivity extends BaseActivity implements IOnHttpListener, View.OnClickListener {

    private TextView tv_title;
    private AutoListView listview;
    private NetRequest netRequest;
    //    //无网络页面
//    private LinearLayout lin_loadfail;
    private ImageView img_fail_nonet;
    private ImageView img_fail_notext;
    private TextView tv_fail;
    private int pageNum = 1;
    private String id;
    private List<OneYuanBuyDetailsBean> list = new ArrayList<>();
    private OneYuanBuyDetailsAdapter adapter;

    private RelativeLayout loadfail;
    private LinearLayout lin_loadNull;//加载为空
    private LinearLayout lin_loadfail;  //无网络页面
    private TextView tvReload;
    private String luckNo;
    private String activityName, shopName, endTime, limitCount, shopPrice, pic, pic_id;
    private TextView quit, re_send;
    private EditText et_remark;
    private TextView tv_ok_submit;
    private RelativeLayout rl_dialog_view;
    private String status;//活动状态

    public static final String ISTRUE = "isTrue";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ExitApplication.getInstance().addActivity(this);
        EventBus.getDefault().register(this);
        setContentView(R.layout.activity_ggl_details);
        id = getIntent().getStringExtra("id");
        luckNo = getIntent().getStringExtra("luck_no");
        activityName = getIntent().getStringExtra("title");
        shopName = getIntent().getStringExtra("shop_name");
        endTime = getIntent().getStringExtra("end_time");
        shopPrice = getIntent().getStringExtra("shop_price");
        limitCount = getIntent().getStringExtra("limit");
        status = getIntent().getStringExtra("status");
        pic = getIntent().getStringExtra("pic");
        pic_id = getIntent().getStringExtra("pic_id");
        initView();
        initData();
        initListeners();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public void onEvent(EventBusBean event) {
        if (event.type == 203) {
            finish();
        }
    }

    private void initData() {
        UserTokenUtils.setUerToken(this);
        netRequest = new NetRequest(this);
        adapter = new OneYuanBuyDetailsAdapter(list, this, status);
        listview.setAdapter(adapter);
        listview.setDivider(null);
    }

    private void initListeners() {
        listview.setOnRefreshListener(new AutoListView.OnRefreshListener() {

            @Override
            public void onRefresh() {
                pageNum = 1;
                netRequest.requestOneYuan_DetailsQuery(2, id, pageNum);
            }
        });

        listview.setOnLoadListener(new AutoListView.OnLoadListener() {

            @Override
            public void onLoad() {
                netRequest.requestOneYuan_DetailsQuery(1, id, pageNum);
            }
        });
        listview.onLoad();
        findViewById(R.id.public_ll_return).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
    }

    DisplayImageOptions options = new DisplayImageOptions.Builder()
            .cacheInMemory(true)
            .showImageOnLoading(R.drawable.default_picture_s)
            .showImageOnFail(R.drawable.default_picture_s)
            .showStubImage(R.drawable.default_picture_s)
            .imageScaleType(ImageScaleType.EXACTLY)
            .bitmapConfig(Bitmap.Config.RGB_565)
            .build();

    private void initView() {
        ((TextView) findViewById(R.id.tv_limit)).setText(Html.fromHtml(String.format(getResources().getString(R.string.limit_count), limitCount)));
        ((TextView) findViewById(R.id.tv_shop_price)).setText(Html.fromHtml(String.format(getResources().getString(R.string.shop_price), shopPrice)));
        ((TextView) findViewById(R.id.tv_end_time)).setText(Html.fromHtml(String.format(getResources().getString(R.string.end_time), endTime)));
        ((TextView) findViewById(R.id.tv_shop_name)).setText(Html.fromHtml(String.format(getResources().getString(R.string.shop_name), shopName)));
        ((TextView) findViewById(R.id.tv_activity_name)).setText(Html.fromHtml(String.format(getResources().getString(R.string.activity_name), activityName)));

        ImageLoader.getInstance().displayImage(pic, (ImageView) findViewById(R.id.iv_icon), options);
        tv_title = (TextView) findViewById(R.id.tvTitle);
        tv_title.setText("详情");
        listview = (AutoListView) findViewById(R.id.onebuy_listview);
        listview.setPageSize(20);
//        lin_loadfail = (LinearLayout) findViewById(R.id.loadfail);
        img_fail_nonet = (ImageView) findViewById(R.id.loadfail_nonet);
        img_fail_notext = (ImageView) findViewById(R.id.loadfail_notext);
//        tv_fail= (TextView) findViewById(R.id.loadfail_tv);


        loadfail = (RelativeLayout) findViewById(R.id.loadfail);

        lin_loadfail = (LinearLayout) findViewById(R.id.ll_load_fail);//无网络
        lin_loadNull = (LinearLayout) findViewById(R.id.ll_load_null);//无网络
        tvReload = (TextView) findViewById(R.id.tv_reload);
        tvReload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Utils.isFastClick()) {
                    return;
                }
                if (adapter != null) {
                    list.clear();
                    adapter.notifyDataSetChanged();
                    pageNum = 1;
                    netRequest.requestOneYuan_DetailsQuery(1, id, pageNum);
                }
            }
        });
        quit = (TextView) findViewById(R.id.quit);
        re_send = (TextView) findViewById(R.id.re_send);


        //取消活动
        quit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rl_dialog_view.setVisibility(View.VISIBLE);

            }
        });
        et_remark = (EditText) findViewById(R.id.et_remark);
        et_remark.setOnClickListener(this);
        tv_ok_submit = (TextView) findViewById(R.id.tv_ok_submit);
        tv_ok_submit.setOnClickListener(this);
        rl_dialog_view = (RelativeLayout) findViewById(R.id.rl_dialog_view);
        rl_dialog_view.setOnClickListener(this);
        //如果活动是进行中，才显示可以取消
        if (status.equals("processing")) {
            quit.setVisibility(View.VISIBLE);
        } else {
            re_send.setVisibility(View.VISIBLE);
            //重新发
            re_send.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(GGLDetailsActivity.this, OneYuanBuy_CreatActivity.class);
                    intent.putExtra("title", activityName);
                    intent.putExtra("shopName", shopName);
                    intent.putExtra("shopPrice", shopPrice);
                    intent.putExtra("limitCount", limitCount);
                    intent.putExtra("pic", pic);
                    intent.putExtra("pic_id", pic_id);
                    startActivity(intent);
                }
            });
            quit.setVisibility(View.GONE);
        }
    }

    @Override
    public void onAfinalFail() {
        listview.onLoadComplete();
        listview.onRefreshComplete();
        showLoadResult(1);
    }

    public void showLoadResult(int state) {
        //无网络情况
        if (state == 1) {
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.VISIBLE);
            lin_loadNull.setVisibility(View.GONE);
        }//无数据情况
        else if (state == 2) {
            Log.v("zyl", "无数据");
            loadfail.setVisibility(View.VISIBLE);
            lin_loadfail.setVisibility(View.GONE);
            lin_loadNull.setVisibility(View.VISIBLE);
        }//都不显示
        else {
            loadfail.setVisibility(View.GONE);
        }
    }

    @Override
    public void onExecuteSuccess(int requestId, String result, String msg) {
        if (requestId == 1) {
            Log.v("mylog", "result:" + result);
            try {
                Type type = new TypeToken<AllBean<OneYuanBuyDetailsBean>>() {
                }.getType();
                Gson gson = new Gson();
                AllBean<OneYuanBuyDetailsBean> allBean = gson.fromJson(result, type);
                listview.onLoadComplete();
                List<OneYuanBuyDetailsBean> list_one = allBean.getList();

                listview.setResultSize(list_one.size());
                list.addAll(list_one);

                JSONObject json = new JSONObject(result);

                if (json.has("page")) {
//                    adapter.setLuckNo(luckNo, json.getJSONObject("page").getString("total_count"));
                }
                adapter.notifyDataSetChanged();
                pageNum += 1;


//                if (list.size() == 0) {
//                    lin_loadfail.setVisibility(View.VISIBLE);
//                    img_fail_nonet.setVisibility(View.GONE);
//                    img_fail_notext.setVisibility(View.VISIBLE);
//                    tv_fail.setText("暂无内容");
//                    showLoadResult(2);
//                }else{
                showLoadResult(3);
//                }

            } catch (Exception e) {
                showLoadResult(1);
                e.printStackTrace();
            }
        } else if (requestId == 2) {
            Log.v("mylog", "ff result:" + result);
            try {
                Type type = new TypeToken<AllBean<OneYuanBuyDetailsBean>>() {
                }.getType();
                Gson gson = new Gson();
                AllBean<OneYuanBuyDetailsBean> allBean = gson.fromJson(result, type);
                List<OneYuanBuyDetailsBean> list_one = allBean.getList();
                listview.onRefreshComplete();
                listview.setResultSize(list_one.size());
                list.clear();
                list.addAll(list_one);
                adapter.notifyDataSetChanged();
                pageNum += 1;
//                if (list.size() == 0) {
//                    lin_loadfail.setVisibility(View.VISIBLE);
//                    img_fail_nonet.setVisibility(View.GONE);
//                    img_fail_notext.setVisibility(View.VISIBLE);
//                    tv_fail.setText("暂无内容");
//                    showLoadResult(2);
//                }else{
                showLoadResult(3);
//                }
            } catch (Exception e) {
                showLoadResult(1);
                e.printStackTrace();
            }
        } else if (requestId == 3) {
            EventBus.getDefault().post(new OneYuanBuyUpdateBean(1));
            rl_dialog_view.setVisibility(View.GONE);
            finish();
            Log.v("zyl", "取消活动成功");
            try {
                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(et_remark.getWindowToken(), 0);
            } catch (Exception e) {
            }
        }
    }

    @Override
    public void onExecuteFail(int requestId, String msg) {
        showLoadResult(1);
        if (requestId == 1) {
            listview.setResultSize(0);
            listview.onLoadComplete();
        } else if (requestId == 2) {
            listview.onRefreshComplete();
        } else if (requestId == 3) {
            ToastUtils.showTextToast(GGLDetailsActivity.this, msg);
            Log.v("zyl", "取消活动失败");
        }
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            //提交
            case R.id.tv_ok_submit:
                String remark = et_remark.getText().toString();
                if (TextUtils.isEmpty(remark)) {
                    ToastUtils.showTextToast(GGLDetailsActivity.this, "请输入活动取消的理由");
                    return;
                } else {
                    netRequest.requestCancelActivity(3, id, remark);
                }
                break;
            case R.id.rl_dialog_view:
                rl_dialog_view.setVisibility(View.GONE);
                break;
        }
    }
}
